//
//  MateKingChoosePhotoViewController.swift

//
//  Created by dongyx on 2023/2/21.
//

import UIKit
import SnapKit
import TZImagePickerController
public enum MateKingChooseItemsType: Equatable {
    
    case videoPic
    case photoPicker
    case videoPicker
    case reportAndBlock(userId: Int,personal:Bool = false)
    case report(userId: Int)
    case delete
    case CallAndReportAndBlock(userId: Int)
    
    var titles: [String] {
        switch self {
        case .videoPic:
            return ["Video","Picture"]
        case .CallAndReportAndBlock:
            return ["Call","Report","Block"]
        case .photoPicker:
            return [" Album upload", " Camera upload"]
        case .videoPicker:
            return [" Album upload", " Camera upload"]
        case .reportAndBlock(_,_):
            return ["Report", "Block"]
        case .delete:
            return ["Delate"]
        case .report(userId: _):
            return ["Report this post"]
        }
    }
    
    var imageNames: [String] {
        switch self {
        case .photoPicker:
            return ["UIImg_More_Album_imageAnt", "UIImg_More_Camera_imageAnt"]
        case .videoPicker:
            return ["UIImg_More_Album_imageAnt", "UIImg_More_Camera_imageAnt"]
        default:
            return [""]
        }
    }
    
    var userId: Int {
        switch self {
        case let .CallAndReportAndBlock(userId):
            return userId
        case let .reportAndBlock(userId,_):
            return userId
        case let .report(userId):
            return userId
        default:
            return 0
        }
    }
    
}

class Edit_Choose_Photo_Interface: UIViewController {
    
    var chooseImageCompletion: ((_ image: UIImage) -> Void)?
    
    var chooseVideoCompletion: ((_ thumbnail: UIImage, _ videoUrl: PHAsset) -> Void)?
    
    private(set) var videoInfo: [String: Any]?
    
    var chooseBlockCompletion: (() -> Void)?
    
    var chooseReportCompletion: (() -> Void)?
    
    var chooseUnfollowedCompletion: (() -> Void)?
    
    var callBlockCompletion: (() -> Void)?

    var videoPickerCompletion: ((Bool) -> Void)?

    var deleteRoomCompletion: (() -> Void)?

    var type: MateKingChooseItemsType = .photoPicker {
        didSet {
            funcView.type = type
        }
    }
    
    private lazy var funcView: MateKingChooseItemsView = {
        let view = MateKingChooseItemsView()
        return view
    }()
    
    var height: CGFloat = 0.0
    
    init(type: MateKingChooseItemsType) {
        super.init(nibName: nil, bundle: nil)
        view.addSubview(funcView)
        self.type = type
        funcView.type = type
        modalTransitionStyle = .crossDissolve
        modalPresentationStyle = .overCurrentContext
        height = CGFloat(type.titles.count) * 50.Fit + 60.Fit + TabbarSafeBottomMargin
        funcView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(height)
            make.bottom.equalTo(height)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        perform(#selector(animatedMove), with: nil, afterDelay: 0.1)
        funcView.cancelBlock = {[weak self] in
            self?.dismissMove()
        }
        funcView.chooseBlock = {[weak self] (itemType, title) in
            if case .photoPicker = self?.type {
                if title == itemType.titles.first {
                    let imagePicker = TZImagePickerController(maxImagesCount: 1, delegate: self)
                    imagePicker?.sortAscendingByModificationDate = false
                    imagePicker?.allowPickingVideo = false
                    imagePicker?.allowPickingOriginalPhoto = false
                    imagePicker?.showPhotoCannotSelectLayer = true
                    imagePicker?.naviBgColor = .black
                    imagePicker?.maxImagesCount = 1
                    imagePicker?.modalPresentationStyle = .fullScreen
                    self?.present(imagePicker!, animated: true, completion: nil)
                }else {
                    let picker = UIImagePickerController()
                    picker.delegate = self
                    picker.sourceType = .camera
                    picker.allowsEditing = true  // 允许拍摄图片后编辑
                    self?.present(picker, animated: true, completion: nil)
                }
            }
            if case .videoPic = self?.type {
                self?.closeController()
                if title == "Video" {
                    guard let closure = self?.videoPickerCompletion else {return}
                    closure(true)
                }else if title == "Picture" {
                    guard let closure = self?.videoPickerCompletion else {return}
                    closure(false)
                }
            }
            if case .delete = self?.type {
                guard let closure = self?.deleteRoomCompletion else {return}
                closure()
            }
            if case .videoPicker = self?.type {
            }
            // 举报和拉黑
            if case .reportAndBlock(let userId,let person) = self?.type {
                if title == "Report" {
                    let view = Report_View()
                    view.person = person
                    view.reportBlock = { content in
                        Toast_View_Tool.show(type: .success,text: "Success!")
                    }
                    let page = Pop_Up_Custom_View(config: PopUpViewConfig(view: view, size: CGSize(width: screenWidth-30.Fit, height: 400.Fit)))
                    page.isCloseFromClean = false
                    page.animatedPop()
                    self?.closeController()
                }else if title == "Call" {
                    guard let closure = self?.callBlockCompletion else {return}
                    closure()
                }else if title == "Block" {
                    let view = Block_View()
                    view.userID = "\(userId)"
                    let page = Pop_Up_Custom_View(config: PopUpViewConfig(view: view, size: CGSize(width: screenWidth-30.Fit, height: 410.Fit)))
                    page.isCloseFromClean = false
                    page.animatedPop()
                    self?.closeController()
                }
            }
                    
            // 选择之后关闭 sheet
            self?.closeAlertSheetView()
            
        }
    }
                    
    private func closeAlertSheetView() {
        funcView.isHidden = true
        UIView.animate(withDuration: 0.3) {[weak self] in
            self?.view.layoutIfNeeded()
            self?.view.backgroundColor = .clear
        }
    }
    
    private func closeController() {
        self.dismiss(animated: false, completion: nil)
    }
    
    @objc private func animatedMove() {
        funcView.snp.remakeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(height)
            make.bottom.equalToSuperview()
        }
        UIView.animate(withDuration: 0.3) {[weak self] in
            self?.view.layoutIfNeeded()
            self?.view.backgroundColor = .blackComponent(0.4)
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismissMove()
    }
    
    func dismissMove() {
        funcView.snp.remakeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(height)
            make.bottom.equalTo(height)
        }
        UIView.animate(withDuration: 0.3) {[weak self] in
            self?.view.layoutIfNeeded()
            self?.view.backgroundColor = .blackComponent(0)
        } completion: {[weak self] isFinish in
            self?.dismiss(animated: false, completion: nil)
        }
    }
    
}

extension Edit_Choose_Photo_Interface:UINavigationControllerDelegate, UIImagePickerControllerDelegate,TZImagePickerControllerDelegate{

    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
        for image in photos {
            guard let closure = self.chooseImageCompletion else {return}
            closure(image)
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image:UIImage!
        image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
        guard let closure = self.chooseImageCompletion else {return}
        closure(image)
        picker.dismiss(animated: true)
    }
    
}


class MateKingChooseItemsView: UIView, UITableViewDelegate, UITableViewDataSource {
    
    var chooseBlock: ((_ type: MateKingChooseItemsType, _ title: String) -> Void)?
    
    var cancelBlock: (() -> Void)?
    var type: MateKingChooseItemsType! {
        didSet {
            addSubview(itemsTableView)
            itemsTableView.snp.makeConstraints { make in
                make.leading.trailing.equalTo(cancelButton)
                make.bottom.equalTo(cancelButton.snp.top).offset(-10.Fit)
                make.height.equalTo(CGFloat(type.titles.count) * 50.Fit)
            }
            itemsTableView.reloadData()
        }
    }
    
    private lazy var cancelButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Cancel", for: .normal)
        btn.setTitleColor(mainColor, for: .normal)
        btn.layer.cornerRadius = 25.Fit
        btn.titleLabel?.font = .setTypeFace(16.Fit,type: .medium)
        btn.backgroundColor = .white
        btn.addTarget(self, action: #selector(mate_action_cancel_actionInfo), for: .touchUpInside)
        return btn
    }()
    
    private lazy var itemsTableView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .white
        view.rowHeight = 50.Fit
        view.layer.cornerRadius = 25.Fit
        view.layer.maskedCorners = .allCorner
        view.register(MateKingSG_MoreItemsCell.self, forCellReuseIdentifier: MateKingSG_MoreItemsCell.description())
        return view
    }()
    
    @objc func mate_action_cancel_actionInfo() {
        guard let closure = cancelBlock else { return }
        closure()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(cancelButton)
        cancelButton.snp.makeConstraints { make in
            make.bottom.equalTo(-TabbarSafeBottomMargin)
            make.leading.equalTo(16.Fit)
            make.trailing.equalTo(-16.Fit)
            make.height.equalTo(50.Fit)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return type.titles.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MateKingSG_MoreItemsCell.description(), for: indexPath) as! MateKingSG_MoreItemsCell
        cell.itemButton.setTitle(type.titles[indexPath.row], for: .normal)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let closure = chooseBlock else { return }
        closure(type, type.titles[indexPath.row])
    }
    
}

class MateKingSG_MoreItemsCell: UITableViewCell {
    
    lazy var itemButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.titleLabel?.font = .setTypeFace(16.Fit,type: .medium)
        btn.setTitleColor(UIColor.color(hexString: "#999999"), for: .normal)
        btn.isUserInteractionEnabled = false
        return btn
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        selectionStyle = .none
        contentView.addSubview(itemButton)
        itemButton.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


class GiftSend_View: UIView {
    
    let iconI = UIImageView.initImgView(img: "picture_gift")
    let sendB = UIButton.initV(img: "button_send")
    let closeB = UIButton.initV(img: "closegift")
    var sendBlock:(() -> Void)?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
        self.subviews {
            iconI
            sendB
            closeB
        }
        
        iconI.left(52.Fit).right(52.Fit).top(NavHeight + 100.Fit).height(305.Fit)
        sendB.width(242.Fit).height(90.Fit)
        sendB.Top == iconI.Bottom + 25.Fit
        sendB.centerHorizontally()
        sendB.addAct {
            self.superview?.animatedDismiss()
            self.sendBlock?()
        }
        
        closeB.Top == sendB.Bottom + 20.Fit
        closeB.size(40.Fit)
        closeB.centerHorizontally()
        closeB.addAct {
            self.superview?.animatedDismiss()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}


class Report_View: UIView {
    
    var reportBlock: ((_ content: String)->Void)?
    var dataSource: [String] = []
    var person = false{
        didSet{
            dataSource = person == true ?
            ["Pornography","Uncivilized language","Dangerous element","Personal attacks"] :
            ["Hate speech","Dangerous organization","Dangerous element","Cyberbullying"]
        }
    }
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .left
        label.text = "Report"
        label.textColor = titleColor
        label.font = .setTypeFace(20,type: .medium)
        return label
    }()
    private lazy var reportListView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separatorStyle = .none
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        view.isScrollEnabled = false
        view.bounces = false
        view.showsVerticalScrollIndicator = false
        view.register(Report_Cell.self, forCellReuseIdentifier: Report_Cell.description())
        return view
    }()
    private lazy var cancelBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Cancle", for: .normal)
        btn.setTitleColor(.color(hexString: "#999999"), for: .normal)
        btn.titleLabel?.font = .setTypeFace(16, type: .medium)
        return btn
    }()
    private lazy var submitBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Submit", for: .normal)
        btn.setTitleColor(.color(hexString: "#EFBF20"), for: .normal)
        btn.titleLabel?.font = .setTypeFace(16, type: .medium)
        btn.backgroundColor = .black
        return btn
    }()
    
    private var selectedIndex: Int?
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        layer.cornerRadius = 25.Fit
        layer.maskedCorners = .allCorner
        addSubview(titleLabel)
        titleLabel.textAlignment = .center
        titleLabel.snp.makeConstraints { make in
            make.leading.equalTo(20.Fit)
            make.trailing.equalTo(-20.Fit)
            make.top.equalTo(20.Fit)
            make.height.equalTo(26)
        }
        
        addSubview(cancelBtn)
        addSubview(submitBtn)
        cancelBtn.snp.makeConstraints { make in
            make.leading.equalTo(20.Fit)
            make.trailing.equalTo(-20.Fit)
            make.bottom.equalTo(-20.Fit)
            make.height.equalTo(50.Fit)
        }
        submitBtn.setAllCorners(corner: 25.Fit)
        submitBtn.snp.makeConstraints { make in
            make.leading.equalTo(20.Fit)
            make.trailing.equalTo(-20.Fit)
            make.height.equalTo(50.Fit)
            make.bottom.equalTo(cancelBtn.snp.top).offset(0)
        }
        cancelBtn.addAct {
            self.superview?.animatedDismiss()
        }
        self.tableView(reportListView, didSelectRowAt: .init(row: 0, section: 0))
        submitBtn.addAct {
            Toast_View_Tool.show()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                if self.selectedIndex != nil {
                    Toast_View_Tool.dismiss()
                    self.reportBlock?("")
                    self.superview?.animatedDismiss()
                }
            }
        }
        addSubview(reportListView)
        reportListView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom)
            make.bottom.equalTo(submitBtn.snp.top).offset(-20.Fit)
        }
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension Report_View: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: Report_Cell.description()) as! Report_Cell
        cell.type = dataSource[indexPath.row]
        cell.selectedBtn.isSelected = indexPath.row == selectedIndex
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedIndex = indexPath.row
        tableView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50.Fit
    }
}


class Report_Cell: UITableViewCell {
    
    var type: String? {
        didSet {
            nameLabel.text = type ?? ""
        }
    }
    
    private lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.color(hexString: "#333333")
        label.font = .systemFont(ofSize: 16)
        return label
    }()
    
    lazy var selectedBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setBackgroundImage(UIImage.init(named: "right 1"), for: .normal)
        btn.setBackgroundImage(UIImage.init(named: "right"), for: .selected)
        return btn
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        selectionStyle = .none
        contentView.addSubview(selectedBtn)
        contentView.addSubview(nameLabel)
        selectedBtn.snp.makeConstraints { make in
            make.trailing.equalTo(-25.Fit)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 15.Fit, height: 15.Fit))
        }
        nameLabel.snp.makeConstraints { make in
            make.leading.equalTo(15.Fit)
            make.top.bottom.equalToSuperview()
            make.trailing.equalTo(selectedBtn.snp.leading).offset(-10.Fit)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
